package com.wx.rpc.client.proxy;

import com.wx.rpc.client.core.IDiscoveryService;
import com.wx.rpc.client.core.RPCTransPort;
import com.wx.rpc.service.request.RPCRequest;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @author wx
 * @Description: 远程调用处理程序
 * @date 2019/3/9 000915:31
 */
public class RemoteInvocationHandler implements InvocationHandler {
    /**
     * 发现服务接口
     */
    private IDiscoveryService discoveryService;

    /**
     * 版本号
     */
    private String version;

    public RemoteInvocationHandler(IDiscoveryService discoveryService, String version) {
        this.discoveryService = discoveryService;
        this.version = version;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //创建RPC请求对象
        RPCRequest request = new RPCRequest();
        request.setClassName(method.getDeclaringClass().getName());
        request.setMethodName(method.getName());
        request.setParameters(args);
        request.setVersion(version);
        String serviceName = request.getClassName();
        if (StringUtils.isBlank(serviceName)){
            throw new RuntimeException("服务不存在");
        }
        if (StringUtils.isNotBlank(version)) {
            serviceName = serviceName + "-" + version;
        }
        String serviceAddress = discoveryService.discovery(serviceName);
        RPCTransPort transformPort = new RPCTransPort(serviceAddress);
        return transformPort.send(request);

    }
}
